package com.sky.service.impl;

import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.mapper.AddressBookMapper;
import com.sky.service.AddressBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class AddressBookServiceImpl implements AddressBookService {
    @Autowired
    private AddressBookMapper addressBookMapper;

    /**
     * 查询地址簿
     *
     * @return
     */
    @Override
    public List<AddressBook> list() {
        AddressBook addressBook = AddressBook.builder()
                .userId(BaseContext.getCurrentId())
                .build();
        List<AddressBook> addressBookList = addressBookMapper.list(addressBook);
        return addressBookList;
    }

    /**
     * 设置默认地址
     * @param id
     */
    @Override
    public void setDefaultAddress(Long id) {
        //设置默认地址业务
        //1.将当前用户的地址全部设置为非默认
        //2.将当前地址设置为默认
        AddressBook addressBook = AddressBook.builder()
                .id(id)
                .userId(BaseContext.getCurrentId())
                .build();
        addressBookMapper.setNotDefaultAddress(addressBook);
        addressBookMapper.setDefaultAddress(addressBook);
    }

    /**
     * 根据id删除地址
     * @param id
     */
    @Override
    public void deleteAddressById(Long id) {
        AddressBook addressBook = AddressBook.builder()
                .id(id)
                .userId(BaseContext.getCurrentId())
                .build();
        addressBookMapper.deleteAddressById(addressBook);
    }

    /**
     * 新增地址
     * @param addressBook
     */
    @Override
    public void saveAddress(AddressBook addressBook) {
        addressBook.setIsDefault(0);
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBookMapper.insert(addressBook);
    }

    /**
     * 查询默认地址
     * @return
     */
    @Override
    public AddressBook queryDefaultAddress() {
        AddressBook addressBook = AddressBook.builder()
                .userId(BaseContext.getCurrentId())
                .build();
        return addressBookMapper.queryDefaultAddress(addressBook);
    }

    /**
     * 根据id查询地址
     * @param id
     * @return
     */
    @Override
    public AddressBook getById(Long id) {
        return addressBookMapper.getById(id);
    }

    /**
     * 修改地址
     * @param addressBook
     */
    @Override
    public void updateAddress(AddressBook addressBook) {
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBookMapper.updateAddress(addressBook);
    }
}
